package Tracker.server.control;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.json.JSONException;
import org.json.JSONObject;

public class UploadController {
	ProtocolHandler handler;

	public UploadController(ProtocolHandler h) {
		this.handler = h;
	}

	public void upload(JSONObject req, JSONObject res) throws JSONException,
			IOException {
		if (!req.isNull("name") && !req.isNull("length")) {
			String fileName = "img/" + req.getString("name");
			int fileLen = req.getInt("length");
			
			BufferedOutputStream image = new BufferedOutputStream(new FileOutputStream(fileName));
			InputStream in = this.handler.client.socket.getInputStream();

			System.out.println("Streaming File");
			byte[] fileBuf = new byte[fileLen];
			int readLen = 0;
			int totalReadLen = 0;
			
			while (totalReadLen < fileLen) {
				readLen = in.read(fileBuf, totalReadLen, (fileBuf.length - totalReadLen));
				if(readLen >= 0) totalReadLen += readLen;
			}
			
			image.write(fileBuf, 0, totalReadLen);
			System.out.println("Stream Complete");

			image.close();
			res.append("success", new Boolean(true));
			return;
		}
	}
}
